package com.blog.security.handler;

import com.alibaba.fastjson2.JSON;
import com.blog.common.CommonRespDto;
import com.blog.common.Constant;
import com.blog.enums.ResponseCodeEnums;
import com.blog.security.config.JwtProperties;
import com.blog.security.entity.AuthUserDetails;
import com.blog.security.util.JwtSecurityUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.WebFilterChainServerAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName CustomAuthenticationSuccessHandler
 * @Destription 自定义 处理“登录成功”的请求
 * @Author 天堂小野花
 * @Date 2025/8/10  14:48
 * @Version 1.0
 */
@Component
public class CustomAuthenticationSuccessHandler extends WebFilterChainServerAuthenticationSuccessHandler {
    public final JwtProperties jwtProperties;

    public CustomAuthenticationSuccessHandler(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Override
    public Mono<Void> onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) {
        ServerWebExchange exchange = webFilterExchange.getExchange();
        ServerHttpResponse response = exchange.getResponse();
        //设置headers
        HttpHeaders headers = response.getHeaders();
        headers.add("Content-Type","application/json;charset=UTF-8");
        headers.add("Cache-Control","no-store,no-cache,must-revalidate,max-age-8");
        //设置body
        CommonRespDto<AuthUserDetails> result = CommonRespDto.successSec();
        byte[] dataBytes ;
        ObjectMapper mapper = new ObjectMapper();
        try {
            AuthUserDetails userDetails = (AuthUserDetails) authentication.getPrincipal();
           /* AuthUserDetails userDetails = buildUser(user);*/
            Map<String, Object> map = new HashMap<>(2);
            map.put(Constant.TOKEN_USER_INFO,userDetails);
            // 生成token
            String jwtToken = JwtSecurityUtil.createJavaWebTokenJwtAuth(map,jwtProperties.getSecretKey(),jwtProperties.getValidateInMs());
            userDetails.setToken(jwtToken);
            result.setData(userDetails);

            dataBytes = mapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            Map<String, Object> map = new HashMap<>(4);
            map.put("status", ResponseCodeEnums.UNAUTHORIZED.getCode());
            map.put("message",ResponseCodeEnums.UNAUTHORIZED.getMessage());
            dataBytes = JSON.toJSONString(map).getBytes();
        }
        DataBuffer bodyDataBuffer = response.bufferFactory().wrap(dataBytes);
        return response.writeWith(Mono.just(bodyDataBuffer));
    }
    /*
    private AuthUserDetails buildUser(User user){
        AuthUserDetails authUserDetails = new AuthUserDetails();
        // 查询数据库用户信息
        authUserDetails.setUsername(user.getUsername());
        authUserDetails.setPassword(new BCryptPasswordEncoder().encode("123456"));
        authUserDetails.setRole("admin");
        return authUserDetails;
    }*/
}
